package cn.schoolwow.workflow.module.task.action.service;

import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickdao.domain.transaction.Transaction;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.check.instance.CheckInstance;
import cn.schoolwow.workflow.domain.task.type.AssignTaskRequest;
import cn.schoolwow.workflow.entity.WorkFlowTask;
import cn.schoolwow.workflow.module.common.flow.AddWorkFlowHistoryFlow;
import cn.schoolwow.workflow.module.task.action.flow.common.CheckWorkFlowTaskExistFlow;

public class AssignTaskServiceFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        checkRequest(flowContext);

        DAO dao = flowContext.checkInstanceData(DAO.class);
        dao.startTransaction(transaction -> {
            flowContext.putTemporaryInstanceData(transaction, Transaction.class);
            updateAssigner(flowContext);
            addHistory(flowContext);
        });
    }

    @Override
    public String name() {
        return "转交工作流实例任务服务流程";
    }

    private void checkRequest(FlowContext flowContext){
        AssignTaskRequest assignTaskRequest = flowContext.checkInstanceData(AssignTaskRequest.class);

        CheckInstance.newCheck()
                .notNullCheck(assignTaskRequest.taskId, "任务id")
                .notEmptyCheck(assignTaskRequest.assigner, "转交人");
        flowContext.startFlow(new CheckWorkFlowTaskExistFlow())
                .putCurrentCompositeFlowData("taskId", assignTaskRequest.taskId)
                .execute();
    }

    private void updateAssigner(FlowContext flowContext){
        AssignTaskRequest assignTaskRequest = flowContext.checkInstanceData(AssignTaskRequest.class);
        Transaction transaction = flowContext.checkInstanceData(Transaction.class);

        transaction.addRecordString("更新工作流任务分配人");
        transaction.query(WorkFlowTask.class)
                .addQuery("id", assignTaskRequest.taskId)
                .addUpdate("assigner", assignTaskRequest.assigner)
                .execute()
                .update();
    }

    private void addHistory(FlowContext flowContext){
        WorkFlowTask workFlowTask = flowContext.checkInstanceData(WorkFlowTask.class);
        AssignTaskRequest assignTaskRequest = flowContext.checkInstanceData(AssignTaskRequest.class);
        Transaction transaction = flowContext.checkInstanceData(Transaction.class);

        transaction.addRecordString("添加转交任务历史记录");
        flowContext.startFlow(new AddWorkFlowHistoryFlow())
                .putCurrentCompositeFlowData("workFlowInstanceId", workFlowTask.getInstanceId())
                .putCurrentCompositeFlowData("message", "转交工作流任务["+workFlowTask.getTaskName()+"]给["+assignTaskRequest.assigner+"]")
                .putCurrentCompositeFlowData("assigner", workFlowTask.getAssigner())
                .execute();
    }
}
